package com.geniusk.security.utils;

import com.geniusk.common.enums.ResponseType;
import com.geniusk.common.exception.GraceException;
import com.geniusk.security.annotation.PreFuncAuth;
import com.geniusk.security.core.LoginUser;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

import java.util.Set;

/**
 * 权限验证工具类
 */
public class AuthUtil {

    /**
     * 获取登陆用户信息，若验证未通过，抛出异常
     */
    public static void checkLogin(){
        LoginUser loginUser = SecurityUtil.getLoginUser();
        if(loginUser.getUserId() == null){
            GraceException.display(ResponseType.UN_LOGIN);
        }
    }

    /**
     * 根据注解传入参数鉴权，若验证未通过，抛出异常
     * @param preAuthorize 权限注解
     */
    public static void checkAuthority(PreFuncAuth preAuthorize) {
        LoginUser loginUser = SecurityUtil.getLoginUser();
        if(!loginUser.getIsRoot()){
            Set<String> permissions = loginUser.getFuncPermissions();
            for(String authorize:preAuthorize.value()){
                boolean hasPermission =  permissions.stream().filter(StringUtils::hasText).anyMatch(x -> PatternMatchUtils.simpleMatch(x, authorize));
                if (!hasPermission){
                    GraceException.display(ResponseType.UNAUTHORIZED);
                }
            }
        }
    }
}